package com.tony.study.thread;

/**
 * Created with IntelliJ IDEA.
 *
 * @Title: ThreadDemo04
 * @Auther: 皮蛋布丁
 * @Date: 2021/10/30/21:50
 * @Description: 多线程同时操作同一个对象（购买火车票）
 * 发现问题：多个线程操作同一个资源的情况下，线程不安全，数据紊乱
 */
public class ThreadDemo04 implements Runnable{

    //票数
    private int ticketNums = 10;

    @Override
    public void run() {
        while (true) {
            if (ticketNums <= 0) {
                break;
            }
            //模拟延时
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+"拿到了第"+ticketNums--+"票");
        }
    }

    public static void main(String[] args) {
        ThreadDemo04 thread = new ThreadDemo04();

        new Thread(thread,"张三").start();
        new Thread(thread,"李四").start();
        new Thread(thread,"黄牛").start();
    }
}
